from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect

from tools.models.models import Admin
from tools.utils.PageData import PageData
from django import forms

from tools.utils.encrypt import md5
from tools.utils.modelform import BootStrapModelForm


def admin_list(request):
    """管理员列表"""

    # 每个view功能都要加，
    # # 检查用户是否已登录，已登录，继续向下走，未登录，跳转到登陆页面
    # # 用户发来请求，获取cookie随即字符串，拿着随即字符串看看session中有么有
    # # request.session['info']
    # info = request.session.get('info')
    # if not info:
    #     return redirect('/tools/login/')

    data_dict = {}
    # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
    search_data = request.GET.get('query', "")
    if search_data:
        data_dict["username__contains"] = search_data

    queryset = Admin.objects.filter(**data_dict).order_by("id")

    # queryset = Admin.objects.all()
    page_object = PageData(request, queryset, page_size=20)
    page_queryset = page_object.page_queryset
    page_string = page_object.page_html()

    context = {
        "page_queryset": page_queryset,
        "page_string": page_string,
        "search_data": search_data,
    }

    return render(request, "testadmin/admin_list.html", context)



class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        # widget=forms.PasswordInput
        # 解决点击保存后,密码和密码确认框中的数据清空问题render_value=True
        widget=forms.PasswordInput(render_value=True),
    )

    class Meta:
        model = Admin
        fields = ["username", "password", "confirm_password"]
        widgets = {
            # 击保存后,密码和密码确认框中的数据清空了,添加一个属性 render_value=True
            "password": forms.PasswordInput(render_value=True),
        }

    # clean_字段名
    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        # return什么.password字段保存什么
        return md5(pwd)

    # 钩子函数
    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = self.cleaned_data.get("confirm_password")
        if md5(confirm) != pwd:
            raise ValidationError("密码不一致!")

        # return返回什么,字段 confirm_password 保存至数据库的值就是什么
        return md5(confirm)


def admin_add(request):
    """添加管理员"""

    title = "新建管理员"

    if request.method == "GET":
        form = AdminModelForm()
        return render(request, "change.html", {"form": form, "title": title})

    # 如果是POST请求
    form = AdminModelForm(data=request.POST)

    context = {
        "form": form,
        "title": title,
    }

    if form.is_valid():
        form.save()
        return redirect("/tools/admin/list")

    return render(request, "change.html", context)




# 如果不想让用户修改密码,只能修改用户名,那么使用下面这个AdminEditModelForm
# 如果都可以修改,直接用上面的AdminModelForm即可
class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = Admin
        fields = ["username"]


def admin_edit(request, nid):
    # 判断 nid 是否存在
    row_object = Admin.objects.filter(id=nid).first()
    if not row_object:
        return render(request, "error.html", {"msg": "数据不存在!"})

    """编辑管理员"""

    title = "编辑管理员"

    if request.method == "GET":
        form = AdminEditModelForm(instance=row_object)
        return render(request, "change.html", {"form": form, "title": title})

    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/tools/admin/list/')

    return render(request, "change.html", {"form": form, "title": title})


def admin_delete(request, nid):
    """删除管理员"""
    Admin.objects.filter(id=nid).delete()
    return redirect("/tools/admin/list/")



class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True),   # 报错后，输入的内容不置空render_value=True
    )

    class Meta:
        model = Admin
        fields = ["password", "confirm_password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    # clean_字段名
    def clean_password(self):
        pwd = self.cleaned_data.get("password")

        # 校验当前数据库中的密码与用户输入的新密码是否一致
        exists = Admin.objects.filter(id=self.instance.pk, password=md5(pwd))
        if exists:
            raise ValidationError("密码不能与当前密码一致!")

        # return什么.password字段保存什么
        return md5(pwd)

    # 钩子函数
    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = self.cleaned_data.get("confirm_password")
        if md5(confirm) != pwd:
            raise ValidationError("密码不一致!")

        # return返回什么,字段 confirm_password 保存至数据库的值就是什么
        return md5(confirm)


def admin_reset(request, nid):
    """重置管理员密码"""

    # 判断 nid 是否存在
    row_object = Admin.objects.filter(id=nid).first()
    if not row_object:
        return render(request, "error.html", {"msg": "数据不存在!"})

    title = "重置密码 - {}".format(row_object.username)

    if request.method == "GET":
        form = AdminResetModelForm(instance=row_object)  # 带上默认值instance=row_object

        return render(request, "change.html", {"title": title, "form": form})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/tools/admin/list/")

    return render(request, "change.html", {"title": title, "form": form})


